package com.ld.rightsSystem.service.impl;

import com.ld.rightsSystem.Enum.ResponseEnum;
import com.ld.rightsSystem.dto.TRoleDTO;
import com.ld.rightsSystem.exception.DBDataNotFoundException;
import com.ld.rightsSystem.filter.JwtRequestFilter;
import com.ld.rightsSystem.mapper.TPermissionRepository;
import com.ld.rightsSystem.mapper.TRoleRepository;
import com.ld.rightsSystem.mapper.TrRolePermissionRepository;
import com.ld.rightsSystem.pojo.TPermission;
import com.ld.rightsSystem.pojo.TRole;
import com.ld.rightsSystem.pojo.TrRolePermission;
import com.ld.rightsSystem.service.inf.TPermissionService;
import com.ld.rightsSystem.service.inf.TRoleService;
import com.ld.rightsSystem.vo.R;
import com.ld.rightsSystem.vo.TRoleVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 角色信息表 服务实现类
 * </p>
 *
 * @author lhb
 * @since 2023-12-27
 */
@Service
public class TRoleServiceImpl implements TRoleService {

    @Autowired
    private JwtRequestFilter jwtRequestFilter;

    @Autowired
    private TRoleRepository tRoleRepository;

    @Autowired
    private TrRolePermissionRepository trRolePermissionRepository;

    @Autowired
    private TPermissionRepository tPermissionRepository;

    /**
     * 添加角色
     * @param tRoleDTO
     * @return
     */
    @Override
    @Transactional
    public R addTRole(TRoleDTO tRoleDTO) {
        Long tRoleIdByRoleName = tRoleRepository.findTRoleIdByRoleName(tRoleDTO.getRoleName());
        if(tRoleIdByRoleName != null){
            return new R().error(ResponseEnum.PARAMS_BINDING_ERROR,null);
        }
        Long tRoleIdByRoleCode = tRoleRepository.findTRoleIdByRoleCode(tRoleDTO.getRoleCode());
        if(tRoleIdByRoleCode != null){
            return new R().error(ResponseEnum.PARAMS_BINDING_ERROR,null);
        }

        TRole tRole = new TRole();
        BeanUtils.copyProperties(tRoleDTO,tRole);
        // 保存角色信息
        tRole.setCreateBy(jwtRequestFilter.userNameThreadLocal.get());
        tRoleRepository.insert(tRole);
        Long roleId = tRoleRepository.findTRoleIdByRoleName(tRole.getRoleName());
        // 保存角色-权限关联信息
        tRoleDTO.getPermissionIds().stream().forEach(id->{
            TPermission tPermission = tPermissionRepository.findTPermissionByPermissionId(id);
            if(tPermission != null){
                TrRolePermission trRolePermission = new TrRolePermission(roleId, id);
                trRolePermissionRepository.save(trRolePermission);
            }
        });
        return new R().OK(null);
    }

    /**
     * 修改角色信息
     * @param tRoleDTO
     * @return
     * @throws DBDataNotFoundException
     */
    @Override
    public R editTRole(TRoleDTO tRoleDTO) throws DBDataNotFoundException {
        TRole tRoleByRoleId = tRoleRepository.findTRoleByRoleId(tRoleDTO.getRoleId());
        if(tRoleByRoleId == null){
            throw new DBDataNotFoundException();
        }
        TRole tRole = new TRole();
        BeanUtils.copyProperties(tRoleDTO,tRole);
        // 保存角色信息
        tRole.setUpdateBy(jwtRequestFilter.userNameThreadLocal.get());
        tRole.setUpdateTime(new Date());
        tRoleRepository.updateTRole(tRole);
        // 删除角色-权限关联信息
        trRolePermissionRepository.deleteTrRolePermissionByRoleId(tRoleByRoleId.getRoleId());
        // 保存角色-权限关联信息
        tRoleDTO.getPermissionIds().stream().forEach(id->{
            TPermission tPermission = tPermissionRepository.findTPermissionByPermissionId(id);
            if(tPermission != null){
                TrRolePermission trRolePermission = new TrRolePermission(tRoleByRoleId.getRoleId(), id);
                trRolePermissionRepository.save(trRolePermission);
            }
        });
        return new R().OK(null);
    }

    /**
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public R getTRoleList(int pageNum, int pageSize) {
        PageRequest pageRequest = PageRequest.of(pageNum - 1,pageSize);
        List<TRole> tRoles = tRoleRepository.findTRolesPageable(pageRequest);
        Map<String,List<TRole>> result = new HashMap<>();
        result.put("list",tRoles);
        return new R().OK(result);
    }

    /**
     * 根据角色编号删除角色
     * @param roleId
     * @return
     * @throws DBDataNotFoundException
     */
    @Override
    public R deleteTRoleById(Long roleId) throws DBDataNotFoundException {
        TRole tRole= tRoleRepository.findTRoleByRoleId(roleId);
        if(tRole != null){
            // 删除角色
            tRoleRepository.deleteTRoleByRoleId(roleId,jwtRequestFilter.userNameThreadLocal.get(),new Date());
            // 删除角色-权限关联信息
            trRolePermissionRepository.deleteTrRolePermissionByRoleId(roleId);
            return new R().OK(null);
        }else {
            throw new DBDataNotFoundException();
        }
    }

    @Override
    public R checkFieldAvailable(String checkRoleName, String checkRoleCode) {
        Map<String,Boolean> result = new HashMap<>();
        Boolean available = false;
        if(checkRoleName != null){
            available = checkRoleNameAvailable(checkRoleName);
            result.put("checkRoleName",available);
        }else if(checkRoleCode != null){
            available = checkRoleCodeAvailable(checkRoleCode);
            result.put("checkPCode",available);
        }
        return new R().OK(result);
    }

    /**
     * 根据角色编号查询详细信息
     * @param roleId
     * @return
     */
    @Override
    public R findRoleInfoByRoleId(Long roleId) throws DBDataNotFoundException {
        // 复制属性值
        TRole tRole = tRoleRepository.findTRoleByRoleId(roleId);
        if(tRole == null){
            throw new DBDataNotFoundException();
        }
        TRoleVO tRoleVO = new TRoleVO();
        BeanUtils.copyProperties(tRole,tRoleVO);
        // 查询角色-权限关联信息
        List<Long> permissionIds = trRolePermissionRepository.findPermissionIdsByRoleId(roleId);
        tRoleVO.setPermissionIds(permissionIds);
        HashMap<String, TRole> result = new HashMap<>();
        result.put("info",tRoleVO);
        return new R().OK(result);
    }

    /**
     * 校验字段是否可用
     * @param checkRoleName
     * @return
     */
    public Boolean checkRoleNameAvailable(String checkRoleName) {
        if(checkRoleName.trim().length() > 0){
            Long roleId = tRoleRepository.findTRoleIdByRoleName(checkRoleName);
            if(roleId != null){
                return false;
            }else {
                return true;
            }
        }else {
            return false;
        }
    }

    /**
     * 校验字段是否可用
     * @param checkRoleCode
     * @return
     */
    public Boolean checkRoleCodeAvailable(String checkRoleCode) {
        if(checkRoleCode.trim().length() > 0){
            Long roleId = tRoleRepository.findTRoleIdByRoleCode(checkRoleCode);
            if(roleId != null){
                return false;
            }else {
                return true;
            }
        }else {
            return false;
        }
    }
}
